package com.x2.core.constant;

import com.x2.modular.system.entity.Dept;
import com.x2.modular.system.entity.User;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class SysTreeNode implements Serializable {
    private String id;
    private String name;
    private String parentId;
    private String value;
    private String type;
    private String selected;
    private String disabled;
    /**
     * 排序号
     */
    private Integer sortNo;
    private List<SysTreeNode> children = new ArrayList<SysTreeNode>();

    public static List<SysTreeNode> createTree(List<SysTreeNode> list) {
        Map<String, SysTreeNode> mapTmp = new HashMap<String, SysTreeNode>();
        //第一级.保证读出来的顺序
        List<String> oneList = new ArrayList<String>();
        for (SysTreeNode current : list) {
            if (StringUtils.isEmpty(current.getParentId()) || "0".equals(current.getParentId())) {
                oneList.add(current.getId());
                mapTmp.put(current.getId(), current);
            }
        }

        for (SysTreeNode node : list) {
            if (!StringUtils.isEmpty(node.getParentId()) && !"0".equals(node.getParentId())) {
                try {
                    mapTmp.get(node.getParentId()).getChildren().add(node);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }

        List<SysTreeNode> finalList = new ArrayList<SysTreeNode>();
        for (String key : oneList) {
            finalList.add(mapTmp.get(key));
        }

        return finalList;
    }

    public static SysTreeNode changeUserNode(User user) {
        SysTreeNode node = new SysTreeNode();
        node.setId(user.getUserId().toString());
        node.setName(user.getName());
//        node.setParentId(baseTrade.getParentId());
        node.setValue(user.getUserId().toString());
//        node.setSortNo(baseTrade.getSortNo());
        return node;
    }

    public static SysTreeNode changeDeptNode(Dept dept, String type) {
        SysTreeNode node = new SysTreeNode();
        node.setId(dept.getDeptId().toString());
        node.setName(dept.getSimpleName());
        node.setValue(dept.getDeptId().toString());
        node.setParentId(dept.getPid().toString());
        if (!StringUtils.isEmpty(type)) {
            node.setType(type);
        }
        node.setSortNo(dept.getSort());
        return node;
    }
    /*public static TreeNode changeNode(BaseTrade baseTrade){
        TreeNode node = new TreeNode();
        node.setId(baseTrade.getId());
        node.setName(baseTrade.getTradeName());
        node.setParentId(baseTrade.getParentId());
        node.setCode(baseTrade.getCode());
        node.setSortNo(baseTrade.getSortNo());
        return node;
    }*/
}
